import React, { useState } from "react"
import { Upload, message, Modal } from "antd"
import { LoadingOutlined, PlusOutlined, } from "@ant-design/icons"
import { uploadFile } from "@/services/common"

import "./uploadImportCss.less"

interface IProps {
  getUrl: (url: string) => void  // 获取上传的图片
}

// 初步上传组件

const upload: React.FC<any> = (props: IProps) => {

  const [loading, setLoading] = useState<boolean>(false)
  const [imageUrl, setImageUrl] = useState<string>("")
  const [imgList, setImgList] = useState<Array<any>>([
    {
      uid: "-1",
      name: "image.png",
      status: "done",
      url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
    }])

  const [previewVisible, setPreviewVisible] = useState<boolean>(false)
  const [previewImage, setPreviewImage] = useState<string>("")




  function beforeUpload(file: any) {
    // 限制图片 格式、size、分辨率
    const isJPG = file.type === "image/jpeg"
    const isJPEG = file.type === "image/jpeg"
    const isGIF = file.type === "image/gif"
    const isPNG = file.type === "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!(isJPG || isJPEG || isPNG)) {
      Modal.error({
        title: "只能上传JPG、JPEG、PNG格式的图片~",
      })
    } else if (!isLt2M) {
      Modal.error({
        title: "图片超过2M限制，不允许上传~",
      })
    }
    return (isJPG || isJPEG || isPNG) && isLt2M

  }

  function getBase64(img: Blob, callback: Function) {
    const reader = new FileReader()
    reader.addEventListener("load", () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  const handleChange = (info: any) => {
    console.log(info)
    if (info.file.status === "error") {
      setLoading(false)
      message.error("上传图片失败")
      return
    }
    if (info.file.status === "uploading") {
      setLoading(true)
      return
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl: string) => {
        setLoading(false)
        // setImageUrl(imageUrl)
        setImgList(info.fileList)
      }
      )
    }
  }


  const handleChange2 = ({ file, fileList }: any) => {

    if (file.status === "removed") {
      setImgList([])
    }
    setImgList(fileList)
  }



  const uploadButton = () => {
    if (loading) {
      return <LoadingOutlined />
    } else {
      return <div><PlusOutlined style={{ fontSize: "24px", color: "#C4C4C4" }} /> <span style={{ position: "absolute", left: "68px", color: "rgba(0, 0, 0, 0.3)" }} >上传头像</span>  </div>
    }
    // return loading ? <LoadingOutlined /> : <PlusOutlined style={{ fontSize: "24px", color: "#C4C4C4" }} />
  }


  // 自定义图片上传
  const doImgUpload = async (options: any) => {
    const { onSuccess, onError, file, onProgress } = options
    console.log("文件：", file)
    // start：进度条相关
    // 伪装成 handleChange里面的图片上传状态
    const imgItem = {
      uid: "1",
      name: "hehe.png",
      status: "uploading",
      url: "",
      percent: 99, // 注意不要写100。100表示上传完成
    }
    setImgList([imgItem])
    // 更新 imgList
    // end：进度条相关

    let File = new FormData()
    File.append("file", file)

    uploadFile(File).then(res => {

      const imgItem2 = {
        uid: file.uid,
        name: file.name,
        status: "success",
        url: res.data.fileUrl, // url 是展示在页面上的绝对链接
        // percent: 100,
        // response: "{\"status\": \"success\"}",
      }
      setImgList([imgItem2])
      setImageUrl(res.data.fileUrl)
      props.getUrl(res.data.fileUrl)
    }).catch(err => {
      return message.error(err.message)
    })

  }


  // 图片预览
  const handlePreview = (imageUrl: any) => {
    setPreviewVisible(true)
    setPreviewImage(imageUrl)
  }

  const handleCancel = () => setPreviewVisible(false)



  return (
    <div className="consultationTeamUpload">
      <Upload
        name="file"
        listType="picture-card"
        className="consultationTeam-uploader"
        showUploadList={false}
        action=""
        beforeUpload={beforeUpload}
        onChange={handleChange}
        customRequest={doImgUpload}
        fileList={imgList}
        onPreview={handlePreview}
      >
        {imageUrl ? <img alt="头像" style={{ width: "100%" }} src={imageUrl} />
          : uploadButton()}
      </Upload>

      {/* {imageUrl ? <img onClick={handlePreview} src={imageUrl} alt="avatar" style={{ width: "60px", height: "60px", borderRadius: "60px" }} /> : null} */}

      <Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
        <img alt="头像" style={{ width: "100%" }} src={imageUrl} />
      </Modal>

    </div >
  )
}

export default upload
